
import {
  SEL_CLASS_CODE,
  SEL_ACTIVE_CODE,
  SYSTEM_INFO,
  USER_INFO,
  CUSTOMER_INFO,
  CUSTOMER_HOTFIX,
  CART_KEY,
  MERCHANT_INFO,
  USER_SPECICAL_INFO,
} from "./constant";
import sensors from "@/js_sdk/Sensorsdata-UniPlugin-JS/Sensorsdata-UniPlugin-JS/index.js";

import commonMorefunLogs from "./commonMorefunLogs.js";

const pageNameJson = {
  // 页面标题翻译
  "app/launch": "app/launch",
  "pages/home/home": "首页",
  "pages/cart/cart": "购物车",
  "pages/info/info": "我的",
  "pages/exploration/exploration": "探索页",

  "pages/item/category": "分类",
  "pages/item/search": "商品列表",
  "pages/item/addressLimit": "限行地址",
  "pages/item/item": "商品详情页",
  "pages/item/itemShare": "商品分享页",
  "pages/item/categoryNew": "商城页",
  "pages/item/itemShare": "商品分享页",
  "pages/item/addressLimit": "限行地址",

  "pages/return/return": "退货列表",
  "pages/return/details": "退货详情",
  "pages/return/applySuccess": "申请成功",
  "pages/store/store": "门店列表",
  "pages/cms/page": "cms落地页",
  "pages/cms/items": "cms商品页",
  "pages/taskCenter/taskCenter": "任务中心页",
  "pages/util/webview": "webview页",
  "pages/util/redirect": "扫码跳转",

  "pages/util/error": "结算异常页面",
  "pages/util/help": "帮助中心政策协议",
  "pages/util/pageNotFound": "页面未找到",

  "pages/memberGift/consult": "顾问邀约",
  "pages/memberGift/applySuccess": "领取详情",

  "pages/order/list": "订单列表",
  "pages/order/paySuccess": "支付成功",
  "pages/order/submit": "确认订单",
  "pages/order/evaluation": "评价页",
  "pages/order/reLogistics": "填写退货物流信息",
  "pages/order/evaluationSuccess": "评价成功",
  "pages/order/details": "订单详情",
  "pages/order/logistics": "物流信息查询",
  "pages/order/submitSuccess": "提交订单成功",

  "pages/GTR/item": "免税专供商品详情页",
  "pages/GTR/storeList": "门店列表",

  "pages/customer/wishList": "心愿单页面",
  "pages/customer/customer": "我",
  "pages/customer/memberGrowth": "会员等级详情",
  "pages/customer/registerSetting": "个人信息",
  "pages/customer/address": "地址管理",
  "pages/customer/evaluation": "评价页面",
  "pages/customer/levelDetailList": "会员等级详情",
  "pages/customer/recordList": "预约列表",
  "pages/customer/webView": "webview页面承载页面",
  "pages/customer/address": "收货地址",
  "pages/customer/settings": "个人信息查看及编辑页面",
  "pages/customer/newJoinMemberModal": "专属注册页面",
  "pages/customer/scanCode": "1v1页面",
  

  "pages/draw/checkSuccess": "登记成功",
  "pages/draw/drawRule": "登记规则",
  "pages/draw/drawSubmit": "提交登记",

  "pages/invoice/apply": "申请发票",
  "pages/invoice/details": "发票详情",
  "pages/invoice/list": "发票列表",
  "pages/invoice/save": "保存发票",

  "pages/search/search": "搜索页",
  "pages/cms/page": "cms落地页",
  "pages/store/store": "门店列表",
  "pages/cms/page": "cms落地页",
  "pages/cms/items": "cms商品页",
  "pages/taskCenter/taskCenter": "任务中心页",
  "pages/special/specialSale": "特殊购买",
  "pages/special/specialSubmit": "特殊购买提交订单",

  "pages/litha/litha": "盈钻首页",
  "pages/litha-launch/official/official": "盈钻关注公众号页面",
  "pages/litha-launch/magazine/index": "盈钻杂志首页",
  "pages/litha-launch/magazine/details": "盈钻杂志详情页",
  "pages/litha-launch/ar/index": "盈钻ar页面",
  "pages/litha-launch/space": "盈钻space页面",
  "pages/litha-launch/game": "盈钻游戏首页",
  "pages/litha-launch/game/details": "盈钻游戏详情页",
  "pages/litha-launch/game/gamePlacard": "盈钻游戏壁纸页",
  "pages/litha-launch/invitation/index": "盈钻邀请函首页",
  "pages/item/categoryList": "商城PLP",
	'pages/item/categoryListTs': 'TSPLP',
	'pages/item/balloutTime': '抽签购PLP'
  ,
	'pages/y200/y200': '200周年落地页'
};

const subscribeMap = {
  SK3jPUiH4huFhLYnT5AU2qCyMeKILHKVBCMfOpft7Hg: "文章更新通知",
  "3biNaYhS0dwQKynRfig5SI5ZEb_RVewTSAd0PE1CqgE": "活动开始提醒",
  u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc: "参与活动结果通知",
  u8hwBNiXZpt6IHeLjh1RltnyutV1f44C8uMtUcRxFOo: "参与活动结果通知",
  "Dh-WY0caxLD6B1NQ2nqRSFMonwROAjinDhd_279boBc": "活动通知",
  "Dh-WY0caxLD6B1NQ2nqRSAmWz4lGXOpVbOQjbNAyKzw": "活动通知",
  "UAOkwlbUpf-1Ha_wb_I9o0AV1e43GCVI-vV97NuB7SE": "商品上新通知",
  "dvgPNQb-7HCYp09b7d-Tc6D6fGkcEOHY_lDOwK89COc": "待付款提醒",
  "4SfLNnxKf26rpT4GO9w4PrrPzlFR40NBjZdOnXHNq8k": "到货提醒",
};
const subscribeTypeMap = {
  SK3jPUiH4huFhLYnT5AU2qCyMeKILHKVBCMfOpft7Hg: "文章",
  "3biNaYhS0dwQKynRfig5SI5ZEb_RVewTSAd0PE1CqgE": "活动",
  u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc: "活动",
  u8hwBNiXZpt6IHeLjh1RltnyutV1f44C8uMtUcRxFOo: "活动",
  "Dh-WY0caxLD6B1NQ2nqRSFMonwROAjinDhd_279boBc": "活动",
  "Dh-WY0caxLD6B1NQ2nqRSAmWz4lGXOpVbOQjbNAyKzw": "活动",
  "UAOkwlbUpf-1Ha_wb_I9o0AV1e43GCVI-vV97NuB7SE": "活动",
  "dvgPNQb-7HCYp09b7d-Tc6D6fGkcEOHY_lDOwK89COc": "订单",
  "4SfLNnxKf26rpT4GO9w4PrrPzlFR40NBjZdOnXHNq8k": "商品",
};
const popupTypeMap = {
  首页开屏弹窗: "宣传",
  品牌故事弹窗: "故事",
  即刻参与登记弹窗: "购买",
  安全校验弹窗: "购买",
  确认登记信息弹窗: "购买",
  确认提交订单弹窗: "购买",
  抽签任务未开始: "抽签任务",
  助力弹窗: "抽签任务",
  助力成功弹窗: "抽签任务",
  助力已完成弹窗: "抽签任务",
  顾问邀约弹窗: "会员权益",
  会员专属权益弹窗: "会员权益",
  限行地址提示弹窗: "限行查询",
  TS活动弹窗: "TS活动",
  半屏加购弹窗: "临时",
  订阅消息弹窗: "订阅消息",
  "18岁弹窗": "用户授权",
  SDK半屏弹窗: "用户授权",
  "18岁弹窗": "用户授权",
  入会弹窗: "会员注册/绑定",
  EB绑定成功弹窗: "会员注册/绑定",
  EB注册成功弹窗: "会员注册/绑定",
  EB绑定成功弹窗: "会员注册/绑定",
  EB注册成功弹窗: "会员注册/绑定",
  注册失败弹窗: "会员注册/绑定",
  注册失败弹窗: "会员注册/绑定",
  非受邀提醒弹窗: "TS活动",
  TS活动未开始弹窗: "TS活动",
  TS活动已结束弹窗: "TS活动",
  TS入会弹窗: "TS活动",
  关闭授权手机号弹窗: "TS活动",
  非受邀老会员提醒弹窗: "TS活动",
  非受邀非会员提醒弹窗: "TS活动",
  TS非受邀入会成功弹窗: "TS活动",
  TS非受邀绑定成功弹窗: "TS活动",
  TS受邀入会成功弹窗: "TS活动",
  TS受邀绑定成功弹窗: "TS活动",
  TS受邀用户绑定失败弹窗: "TS活动",
  TS受邀用户注册失败弹窗: "TS活动",
  心愿单添加成功弹窗: "意向登记",
  登记成功弹窗: "意向登记",
  订阅失败弹窗: "意向登记",
  取消登记弹窗: "意向登记",
};

const customerTrack = (vthis, en, ep) => {
  return new Promise((resolve) => {});
};
const commonTrack = (vthis, type, en, ep) => {
  return new Promise((resolve) => {});
};
function commonRegister(en, ep) {
  if (en == "utm" && !!ep.utm_source) {
    sensors.register({
      utm_campaign: decodeURIComponent(ep.utm_campaign),
      utm_source: decodeURIComponent(ep.utm_source),
      utm_medium: decodeURIComponent(ep.utm_medium),
      utm_term: decodeURIComponent(ep.utm_term),
      utm_content: decodeURIComponent(ep.utm_content),
    });
  }
}
async function commonUtmRegister(en, ep) {
  const firstUtm = await dealFirstUtm(ep.query || "");
  const latestUtm = await dealLatestUtm(ep.query || "");
  const utmParams = {
    utm_campaign: ep.query.utm_campaign
      ? decodeURIComponent(ep.query.utm_campaign)
      : "",
    utm_source: ep.query.utm_source
      ? decodeURIComponent(ep.query.utm_source)
      : "",
    utm_medium: ep.query.utm_medium
      ? decodeURIComponent(ep.query.utm_medium)
      : "",
    utm_term: ep.query.utm_term ? decodeURIComponent(ep.query.utm_term) : "",
    utm_content: ep.query.utm_content
      ? decodeURIComponent(ep.query.utm_content)
      : "",
    ...latestUtm,
    ...firstUtm,
  };
  sensors.register(utmParams);
	//	莫凡日志
	commonMorefunLogs.aliYunMorefunLogs({
	  ...utmParams,
		msg: "神策注册-utm-register"
	})
}
//  处理first_utm数据
async function dealFirstUtm(query) {
  const _firstUtm = uni.getStorageSync("firstUtmKey");
  if (_firstUtm) {
    for (let key in _firstUtm) {
      if (_firstUtm.hasOwnProperty(key)) {
        _firstUtm[key] = decodeURIComponent(_firstUtm[key]);
      }
    }
    return _firstUtm;
  }

  if (query && query.utm_campaign) {
    const _obj = {
      first_utm_campaign: query.utm_campaign
        ? decodeURIComponent(query.utm_campaign)
        : "",
      first_utm_source: query.utm_source
        ? decodeURIComponent(query.utm_source)
        : "",
      first_utm_medium: query.utm_medium
        ? decodeURIComponent(query.utm_medium)
        : "",
      first_utm_term: query.utm_term ? decodeURIComponent(query.utm_term) : "",
      first_utm_content: query.utm_content
        ? decodeURIComponent(query.utm_content)
        : "",
    };
    uni.setStorageSync("firstUtmKey", _obj);
    return _obj;
  }

  return {
    first_utm_campaign: query.utm_campaign
      ? decodeURIComponent(query.utm_campaign)
      : "",
    first_utm_source: query.utm_source
      ? decodeURIComponent(query.utm_source)
      : "",
    first_utm_medium: query.utm_medium
      ? decodeURIComponent(query.utm_medium)
      : "",
    first_utm_term: query.utm_term ? decodeURIComponent(query.utm_term) : "",
    first_utm_content: query.utm_content
      ? decodeURIComponent(query.utm_content)
      : "",
  };
}
// 处理 latest_utm数据
async function dealLatestUtm(query) {
  //  url存在utm参数，直接返回当前，并且存储本地缓存
  if (query && query.utm_campaign) {
    const _obj = {
      latest_utm_campaign: query.utm_campaign
        ? decodeURIComponent(query.utm_campaign)
        : "",
      latest_utm_source: query.utm_source
        ? decodeURIComponent(query.utm_source)
        : "",
      latest_utm_medium: query.utm_medium
        ? decodeURIComponent(query.utm_medium)
        : "",
      latest_utm_term: query.utm_term ? decodeURIComponent(query.utm_term) : "",
      latest_utm_content: query.utm_content
        ? decodeURIComponent(query.utm_content)
        : "",
    };
    uni.setStorageSync("latestUtmKey", _obj);
    return _obj;
  }
  //  url无utm参数，获取本地缓存并返回
  const _latestUtm = uni.getStorageSync("latestUtmKey");
  if (_latestUtm) {
    for (let key in _latestUtm) {
      if (_latestUtm.hasOwnProperty(key)) {
        _latestUtm[key] = decodeURIComponent(_latestUtm[key]);
      }
    }
    return _latestUtm;
  }
  //  url和本地缓存均无utm 直接返回空
  return {
    latest_utm_campaign: "",
    latest_utm_source: "",
    latest_utm_medium: "",
    latest_utm_term: "",
    latest_utm_content: "",
  };
}

function loginWithKey(ep) {
  if (!!ep) {
    // sensors.loginWithKey("$identity_login_id", `${ep}`);
    sensors.login(`${ep}`);
  }
	// 莫凡日志
	commonMorefunLogs.aliYunMorefunLogs({
		msg: "commonSensors-loginWithKey-神策登录",
		id: String(ep)
	})
}
function bind(en, ep) {
  if (en == "utm" && !!ep.utm_source) {
    sensors.register({
      utm_campaign: decodeURIComponent(ep.utm_campaign),
      utm_source: decodeURIComponent(ep.utm_source),
      utm_medium: decodeURIComponent(ep.utm_medium),
      utm_term: decodeURIComponent(ep.utm_term),
      utm_content: decodeURIComponent(ep.utm_content),
    });
		//	莫凡日志
		commonMorefunLogs.aliYunMorefunLogs({
      utm_campaign: decodeURIComponent(ep.utm_campaign),
      utm_source: decodeURIComponent(ep.utm_source),
      utm_medium: decodeURIComponent(ep.utm_medium),
      utm_term: decodeURIComponent(ep.utm_term),
      utm_content: decodeURIComponent(ep.utm_content),
			msg: "神策注册-utm-register"
    })
  }else{
		//	莫凡日志
		commonMorefunLogs.aliYunMorefunLogs({
			data: JSON.stringify(ep),
			msg: "神策注册-utm-register-error"
		})
	}
}
//神策埋点传递公共属性给ar页面
let _commonProfile = {
  is_member: false,
  is_new_member: false,
  register_platform: "",
};

function commonSetProfile(type, ep) {
  if (!!ep) {
    if (type == "customer") {
      _commonProfile.is_member = true;
      sensors.setProfile({
        custom_id: ep.customerId || "",
        is_member: true,
      });
      sensors.register({
        is_member: true,
      });
      if (!!ep.customerId) {
        sensors.bind("identity_eb_customer_id", ep.customerId);
      }
			let _mobile = "";
      if (!!ep.mobile) {
        sensors.bind("$identity_mobile", ep.mobile);
				const _m2 = String(ep.mobile);
				_mobile = _m2.replace(_m2.substring(3,7), '****');
      }
			//	莫凡日志
			commonMorefunLogs.aliYunMorefunLogs({
				type:"customer",
				usermobile: _mobile,
				custom_id: ep.customerId ? String(ep.customerId) : "",
				is_member: "true",
			  identity_eb_customer_id: String(ep.customerId),
				msg: "神策注册-commonSetProfile-setProfile-bind"
			})
    } else if (type == "member") {
			if (!!ep.id) {
				const customer = uni.getStorageSync(CUSTOMER_INFO);
			  // sensors.loginWithKey("$identity_login_id", `${ep.id}`);
				sensors.login(`${ep.id}`);
				//	神策建议 login之后清除掉之前bind进来的id信息是我们正常的逻辑。我们也建议在login()之后重新bind()准确绑定和标识用户信息
				if (!!customer.unionId) {
				  sensors.bindUnionid(customer.unionId);
				}
				
				let _mobile = "";
				if (!!customer.mobile) {
				  sensors.bind("$identity_mobile", customer.mobile);
					const _m2 = String(ep.mobile);
					_mobile = _m2.replace(_m2.substring(3,7), '****');
				}
				if (!!customer.openId) {
				  sensors.bindOpenid(customer.openId);
				}
			  sensors.bind("identity_crm_customer_id", `${ep.id}`);
				if (!!customer.customerId) {
				  sensors.bind("identity_eb_customer_id", customer.customerId);
				}
				//	莫凡日志
				commonMorefunLogs.aliYunMorefunLogs({
					usermobile: _mobile,
					is_member: "true",
				  identity_eb_customer_id: String(customer.customerId),
					identity_crm_customer_id: String(ep.id),
					bindOpenid: customer.openId,
					bindUnionid: customer.unionId,
					login: String(ep.id),
					msg: "神策注册-login"
				})
			}
      const _isNewMember = ep.isNewMember ? true : false;
      const _registerPlatform = ep.source ? ep.source : "";
      _commonProfile.is_member = true;
      _commonProfile.is_new_member = _isNewMember;
      _commonProfile.register_platform = _registerPlatform;
      let _obj1 = {
        custom_id: ep.customerId || "",
        is_member: true,
        is_new_member: _isNewMember,
        register_platform: _registerPlatform,
        member_level: ep.memberLevelId || "",
        country: ep.country || "",
        province: ep.province || "",
        city: ep.city || "",
        gender: ep.gender || "",
        permanent_address: ep.city
          ? ep.province
            ? `${ep.province}省${ep.city}市`
            : `${ep.city}市`
          : "",
      };
      if (!!ep.birthDay) {
        _obj1.birthday = ep.birthDay;
      }
      sensors.setProfile(_obj1);
      let _obj2 = {
        is_member: true,
        is_new_member: _isNewMember,
      };
      if (_registerPlatform) {
        _obj2.register_platform = ep.source;
      }
      sensors.register(_obj2);
			//	莫凡日志
			commonMorefunLogs.aliYunMorefunLogs({
				is_member: "true",
				is_new_member: _isNewMember ? "true" :"false",
				type: "member",
				register_platform: _registerPlatform,
				custom_id: ep.customerId ? String(ep.customerId) : "",
				msg: "commonSensors-commonSetProfile-member"
			})
    }
  } else {
    _commonProfile.is_member = false;
    _commonProfile.is_new_member = false;
    sensors.setProfile({
      is_member: false,
      is_new_member: false,
    });
		//	莫凡日志
		commonMorefunLogs.aliYunMorefunLogs({
			is_member: "false",
			is_new_member: "false",
			msg: "commonSensors-commonSetProfile-ep为空"
		})
  }
}
function noMember() {
  // console.log('访客登录上报')
  sensors.register({
    is_member: false,
    is_new_member: false,
  });

  sensors.setProfile({
    is_member: false,
    is_new_member: false,
  });
  // console.log('访客登录上报end')
}
function bindOpenid(ep) {
  if (!!ep) {
    sensors.bindOpenid(ep);
  }
}
function bindUnionid(ep) {
  if (!!ep) {
    sensors.bindUnionid(ep);
  }
}
function binduserid(openid, unionId) {
  if (!!openid) {
    sensors.bindOpenid(openid);
  }
  if (!!unionId) {
    sensors.bindUnionid(unionId);
  }
	//	莫凡日志
	commonMorefunLogs.aliYunMorefunLogs({
		openid: openid,
		unionId: unionId,
		msg: "commonSensors-binduserid"
	})
}

function registerPopupExposure(popupName) {
  sensors.track("RegisterPopupExposure", {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    popup_name: popupName,
  });
}

function commonPopupClick(eventName, popupName, buttonName) {
  sensors.track(eventName, {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    popup_name: popupName,
    button_name: buttonName,
  });
}
function registerAuthorization(authorType, isSuccess) {
  sensors.track("RegisterAuthorization", {
    author_type: authorType,
    is_success: isSuccess,
  });
}
function commonPageView(eventName, referUrl) {
  sensors.track(eventName, {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    refer_source: referUrl
      ? pageNameJson[referUrl]
      : getCurrentPages().length > 1
      ? pageNameJson[getCurrentPages()[getCurrentPages().length - 2].route]
      : "",
    refer_url: referUrl
      ? referUrl
      : getCurrentPages().length > 1
      ? getCurrentPages()[getCurrentPages().length - 2].route
      : "",
  });
}

function commonPageClick(eventName, buttonName) {
  sensors.track(eventName, {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    button_name: buttonName,
  });
}
function simpleTrack(eventName, reportPath, eventParams) {
  let ep = eventParams;
  if (reportPath) {
    let currentPathParams = {
      page_name:
        pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    };
    ep = Object.assign({}, eventParams, currentPathParams);
  }
  sensors.track(eventName, ep);
}
function cmsExposeTrack(eventName, eventParams, reportPath) {
  let ep = eventParams;
  if (reportPath) {
    let currentPathParams = {
      page_name:
        pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    };
    ep = Object.assign({}, eventParams, currentPathParams);
  }
  sensors.track(eventName, ep);
}

/**
 * @param {Object} item 商品数据
 * @param {Object} index 下标
 * @param {Object} navName 模块名称
 * @param {Object} tab_name tab名称
 */
function PLPProductClick(item, index, navName, tab_name) {
  let ep = {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    module_name: navName
      ? navName
      : getCurrentPages()[getCurrentPages().length - 1].data.navName || "",
    tab_name,
    // product_category_level1: navInfo.navName,
    product_purchase_type:
      navName == "不凡甄选"
        ? ["抽签"]
        : navName == "免税专供"
        ? ["免税商品"]
        : ["常规"],
    product_sku_id: !!item.skuCodes ? item.skuCodes[0] : "",
    product_spu_id: item.outerItemId || "",
    product_name: item.itemName,
    product_position: typeof index == "number" ? index + 1 : "",
    product_variant: item.valueName || item.specification,
    product_price: item.price || "",
  };
  sensors.track("PLPProductClick", ep);
}

function pdpEvent(
  eventName,
  item,
  buttonName,
  purchaseType,
  isSoldOut,
  isDrawWin
) {
  let ep = {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    refer_source:
      getCurrentPages().length > 1
        ? pageNameJson[getCurrentPages()[getCurrentPages().length - 2].route]
        : "",
    refer_url:
      getCurrentPages().length > 1
        ? getCurrentPages()[getCurrentPages().length - 2].route
        : "",
    // product_category_level1: navInfo.navName,
    product_purchase_type: purchaseType,
    product_spu_id: item.outerItemId || "",
    product_sku_id: !!item.skus ? item.skus[0].skuCode : "",
    product_name: item.itemName,
    // product_position: index + 1,
    product_variant: !!item.skus
      ? item.skus[0].skuProperties[0].valueName
      : !!item.valueName
      ? item.valueName
      : !!item.specification
      ? item.specification
      : "",
    product_price: !!item.skus
      ? item.skus[0].price
      : !!item.price
      ? item.price
      : "",
    is_drawn: isDrawWin || false,
    is_allow_purchased: isDrawWin || false,
    is_soldout: isSoldOut || false,
  };
  if (!!buttonName) {
    ep = Object.assign(ep, {
      button_name: buttonName,
    });
  }
  sensors.track(eventName, ep);
}
function registerButtonClick(entranceName) {
  let ep = {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    refer_source:
      getCurrentPages().length > 1
        ? pageNameJson[getCurrentPages()[getCurrentPages().length - 2].route]
        : "",
    refer_url:
      getCurrentPages().length > 1
        ? getCurrentPages()[getCurrentPages().length - 2].route
        : "",
    entrance_name: entranceName,
  };
  sensors.track("RegisterButtonClick", ep);
}
function popupEvent(eventName, eventParams) {
  let ep = {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
  };
  ep = Object.assign(ep, eventParams);
  sensors.track(eventName, ep);
}
function memberInfoCompetePageClick(buttonName, isSave) {
  let ep = {
    button_name: buttonName,
    is_save: isSave,
  };
  sensors.track("MemberInfoCompetePageClick", ep);
}
function addToCart(detail, num, purchaseType) {
  let ep = {
    product_purchase_type: purchaseType,
    product_spu_id: detail.outerItemId || "",
    product_sku_id: !!detail.skus ? detail.skus[0].skuCode : "",
    product_name: detail.itemName,
    product_variant: !!detail.skus
      ? detail.skus[0].skuProperties[0].valueName
      : "",
    product_quantity: num,
    product_price: !!detail.skus ? detail.skus[0].price : "",
  };
  sensors.track("AddToCart", ep);
}
function addToCartMF(detail, num, purchaseType) {
  let ep = {
    product_purchase_type: purchaseType,
    product_spu_id: detail.outerItemId || "",
    product_sku_id: !!detail.skuCodes.length ? detail.skuCodes[0] : "",
    product_name: detail.itemName,
    product_variant: !!detail.valueName ? detail.valueName : "",
    product_quantity: num,
    product_price: !!detail.price ? detail.price : "",
  };
  sensors.track("AddToCart", ep);
}
function editCart(detail, num, purchaseType, type) {
  let ep = {
    product_purchase_type: purchaseType,
    product_spu_id: detail.outerItemId || "",
    product_sku_id: detail.skuCode,
    product_name: detail.itemName,
    product_variant: !!detail.skuProperties
      ? detail.skuProperties[0].valueName
      : "",
    edit_type: type,
    edit_quantity: num,
  };
  sensors.track("EditCart", ep);
}
function commonOrderView(eventName, list) {
  let spuList = [];
  let skuList = [];
  let nameList = [];
  let productQuantity = 0;
  list.forEach(function (item, index, array) {
    productQuantity += item.qty;
    nameList.push(item.itemName);
    skuList.push(item.skuCode);
    spuList.push(item.outerItemId);
  });
  let ep = {
    product_quantity: productQuantity,
    product_sku_quantity: list.length,
    product_spu_list: spuList,
    product_sku_list: skuList,
    product_name_list: nameList,
  };
  sensors.track(eventName, ep);
}
function saveByCartTrack(orderId, orderDetail, list, address, isDraw) {
  let productQuantity = 0;
  let entranceType =
    getCurrentPages().length > 1 &&
    getCurrentPages()[getCurrentPages().length - 2].route == "pages/item/item"
      ? "商品详情页"
      : "购物车";
  list.forEach(function (item, index, array) {
    productQuantity += item.qty;
    sensors.track("BeginCheckoutDetail", {
      order_id: orderId,
      entrance_type: entranceType,
      delivery_province: address.receiverState || "",
      delivery_city: address.receiverCity || "",
      product_purchase_type: isDraw
        ? ["抽签"]
        : !!item.tsActivityMark
        ? ["特殊"]
        : ["常规"],
      product_spu_id: item.outerItemId || "",
      product_sku_id: item.skuCode,
      product_name: item.itemName,
      product_variant: item.skuProperties[0].valueName,
      product_quantity: item.qty,
      product_price: item.price,
    });
  });
  let ep = {
    order_id: orderId,
    entrance_type: entranceType,
    delivery_province: address.receiverState || "",
    delivery_city: address.receiverCity || "",
    product_sku_quantity: list.length,
    product_quantity: productQuantity,
    order_amount: orderDetail.payment,
  };
  sensors.track("BeginCheckout", ep);
}
function commonCancelOrder(orderDetail) {
  // let productQuantity = 0
  // orderDetail.items.forEach(function(item, index, array) {
  //   productQuantity += item.qty
  //   sensors.track('CancelOrderDetail', {
  //     order_id: orderDetail.orderCode,
  //     cancel_reason: '主动取消',
  //     delivery_province: orderDetail.receiverState,
  //     delivery_city: orderDetail.receiverCity,
  //     product_purchase_type: !!orderDetail.addition?.activitySelectionId ? ['抽签'] : !!item.tsActivityMark ? ['特殊'] : ['常规'],
  //     pay_method: orderDetail.payType == "wosai:litepos:purchase" ? '支付宝' : '微信',
  //     product_spu_id: item.outerItemId || '',
  //     product_sku_id: item.skuCode,
  //     product_name: item.itemName,
  //     product_variant: item.skuProperties[0].valueName,
  //     product_quantity: item.qty,
  //     product_price: item.price,
  //   })
  // });
  // let ep = {
  //   order_id: orderDetail.orderCode,
  //   cancel_reason: '主动取消',
  //   delivery_province: orderDetail.receiverState,
  //   delivery_city: orderDetail.receiverCity,
  //   product_purchase_type: !!orderDetail.addition?.activitySelectionId ? ['抽签'] : !!orderDetail.items[0].tsActivityMark ? ['特殊'] : ['常规'],
  //   pay_method: orderDetail.payType == "wosai:litepos:purchase" ? '支付宝' : '微信',
  //   product_sku_quantity: orderDetail.items.length,
  //   product_quantity: productQuantity,
  //   order_amount: orderDetail.payment
  // }
  // sensors.track('CancelOrder', ep)
}
function orderDetailPageView(orderDetail) {
  orderDetail.items.forEach(function (item, index, array) {
    sensors.track("OrderDetailPageView", {
      order_id: orderDetail.orderCode,
      delivery_province: orderDetail.receiverState,
      delivery_city: orderDetail.receiverCity,
      product_purchase_type:
        orderDetail.addition?.tsActivityLimitList?.length > 0 &&
        orderDetail.addition.tsActivityLimitList[0].hasLimitPurchase
          ? ["特殊"]
          : !!item.tsActivityMark
          ? ["特殊"]
          : !!orderDetail.addition?.activitySelectionId
          ? ["抽签"]
          : ["常规"],
      pay_method:
        orderDetail.payType == "wosai:litepos:purchase" ? "支付宝" : "微信",
      product_spu_id: item.outerItemId || "",
      product_sku_id: item.skuCode,
      product_name: item.itemName,
      product_variant: item.skuProperties[0].valueName,
      product_quantity: item.qty,
      product_price: item.price,
    });
  });
}
function orderPageView(orderDetail, tabName) {
  let productQuantity = 0;
  let productSkuQuantity = 0;
  let spuList = [];
  let skuList = [];
  let nameList = [];
  let orderIdList = [];
  orderDetail.forEach(function (item, index, array) {
    productSkuQuantity += item.items.length;
    orderIdList.push(item.orderCode);
    item.items.forEach(function (innerItem, innerIndex, innerArray) {
      productQuantity += innerItem.qty;
      nameList.push(innerItem.itemName);
      skuList.push(innerItem.skuCode);
      spuList.push(innerItem.outerItemId);
    });
  });
  let ep = {
    tab_name: tabName,
    order_id_list: orderIdList,
    product_spu_list: spuList,
    product_sku_list: skuList,
    product_name_list: nameList,
    product_quantity: productQuantity,
    product_sku_quantity: productSkuQuantity,
  };
  sensors.track("OrderPageView", ep);
}
function drawSensorsTrack(eventName, detail, purchaseType) {
  let ep = {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    product_purchase_type: ["抽签"],
    product_spu_id: detail.outerItemId || "",
    product_sku_id: !!detail.skus ? detail.skus[0].skuCode : "",
    product_name: detail.itemName,
    product_variant: !!detail.skus
      ? detail.skus[0].skuProperties[0].valueName
      : "",
    product_price: !!detail.skus ? detail.skus[0].price : "",
  };
  sensors.track(eventName, ep);
}
function drawSuccessTrack(eventName, detail, purchaseType) {
  let ep = {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    product_purchase_type: ["抽签"],
    product_spu_id: detail.spuId || "",
    product_sku_id: detail.skuCode || "",
    product_name: detail.itemName,
    product_variant: detail.productVariant || "",
    product_price: detail.price || "",
  };
  sensors.track(eventName, ep);
}
function searchActive(act_method) {
  sensors.track("Search", { act_method });
}
function searchResult(keyWord, type, detail, act_method = "") {
  let ep = {
    keyword: keyWord,
    has_result: detail?.length > 0,
    search_method: type,
    search_result_quantity: detail?.length,
    // act_method: act_method
  };
  sensors.track("SearchResult", ep);
}


function paramsTrack(type, searchParams) {
  sensors.track(type, searchParams);
}


function giftsDetailTrack(type,params) {
  params.current_url = getCurrentPages()[getCurrentPages().length - 1].route;
  sensors.track(type, params);
}

function searchResultClick(keyWord, type, detail) {
  let ep = {
    keyword: keyWord,
    search_method: type,
    product_spu_id: detail.outerItemId || "",
    product_sku_id: !!detail.skuCodes ? detail.skuCodes[0] : "",
    product_name: detail.itemName,
    product_variant: detail.valueName,
    product_price: detail.price,
  };
  sensors.track("SearchResultClick", ep);
}
function sensorsPageShare() {
  sensors.track("PageShare", {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
  });
}
function addressManagement() {
  sensors.track("AddressManagement");
}
function modelAuthAsk(sceneName, idsArr) {
  let namesArr = [];
  idsArr.forEach(function (item, index, array) {
    namesArr.push(!!subscribeMap[item] ? subscribeMap[item] : sceneName);
  });
  let ep = {
    scene_name: !!subscribeTypeMap[idsArr[0]]
      ? subscribeTypeMap[idsArr[0]]
      : !!subscribeMap[idsArr[0]]
      ? subscribeMap[idsArr[0]]
      : sceneName,
    models_id: idsArr,
    models_name: namesArr,
  };

  sensors.track("ModelAuthAsk", ep);
}
function homePageEvent(eventName, eventParams) {
  let ep = Object.assign({}, eventParams, {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    refer_source:
      getCurrentPages().length > 1
        ? pageNameJson[getCurrentPages()[getCurrentPages().length - 2].route]
        : "",
    refer_url:
      getCurrentPages().length > 1
        ? getCurrentPages()[getCurrentPages().length - 2].route
        : "",
  });
  sensors.track(eventName, ep);
}
function commentTrack(arr, objArr) {
  arr.forEach(function (item, index, array) {
    sensors.track("Comment", {
      page_name:
        pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
      product_spu_id: item.spuId,
      product_sku_id: item.skuCode,
      product_name: item.skuInfo.itemName,
      product_variant: item.skuInfo.itemCapacity,
      product_price: objArr[index].price,
      star_rank: item.itemScore,
    });
  });
}
function consultantInvitationClick(actName) {
  let ep = {
    invitation_name: actName,
  };
  sensors.track("ConsultantInvitationClick", ep);
}
function followClick() {
  sensors.track("FollowClick");
}
function setProfileAddress(addressList) {
  let ep = {
    delivery_address: addressList,
  };
  sensors.setProfile(ep);
}
function bannerTrack(eventName, reportPath, eventParams) {
  let ep = eventParams;
  if (reportPath) {
    let currentPathParams = {
      page_name:
        pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    };
    ep = Object.assign({}, eventParams, currentPathParams);
  }
  sensors.track(eventName, ep);
}
function contentPageView(eventName, eventParams) {
  let ep = Object.assign({}, eventParams, {
    page_name:
      pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route],
    current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    refer_source:
      getCurrentPages().length > 1
        ? pageNameJson[getCurrentPages()[getCurrentPages().length - 2].route]
        : "",
    refer_url:
      getCurrentPages().length > 1
        ? getCurrentPages()[getCurrentPages().length - 2].route
        : "",
  });
  sensors.track(eventName, ep);
}

//  获取神策sdk预置属性
function getSdkPresetProperties() {
  try {
    if (sensors && sensors.instance) {
      return sensors.instance.getPresetProperties();
    } else {
      return null;
    }
  } catch (e) {
    return null;
  }
}

// litha神策埋点
const lithaTrack = {
  memberInfo: () => {
    return _commonProfile;
  },
  crTrack: (eventName, eventParams) => {
    let ep = Object.assign({}, eventParams, {
      page_name: eventParams?.page_name
        ? eventParams?.page_name
        : pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route] ||
          "",
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
      refer_source: eventParams?.refer_url
        ? pageNameJson[eventParams?.refer_url]
        : getCurrentPages().length > 1
        ? pageNameJson[getCurrentPages()[getCurrentPages().length - 2].route]
        : "",
      refer_url: eventParams?.refer_url
        ? eventParams?.refer_url
        : getCurrentPages().length > 1
        ? getCurrentPages()[getCurrentPages().length - 2].route
        : "",
    });
    sensors.track(eventName, ep);
  },
  cTrack: (eventName, eventParams) => {
    let ep = Object.assign({}, eventParams, {
      page_name: eventParams?.page_name
        ? eventParams?.page_name
        : pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route] ||
          "",
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    });
    sensors.track(eventName, ep);
  },
  tabbarClick: (eventParams) => {
    sensors.track("TabbarClick", eventParams);
  },
  floatIconClick: () => {
    let ep = Object.assign(
      {},
      {
        page_name:
          pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route] ||
          "",
        current_url: getCurrentPages()[getCurrentPages().length - 1].route,
      }
    );
    sensors.track("FloatIconClick", ep);
  },
  popupClick: (eventParams) => {
    let ep = Object.assign({}, eventParams, {
      page_name:
        pageNameJson[getCurrentPages()[getCurrentPages().length - 1].route] ||
        "",
      current_url: getCurrentPages()[getCurrentPages().length - 1].route,
    });
    sensors.track("PopupExposure", ep);
  },
};

module.exports = {
  addToCartMF,
  lithaTrack,
  customerTrack,
  commonTrack,
  commonRegister,
  commonUtmRegister,
  loginWithKey,
  bind,
  bindOpenid,
  bindUnionid,
  binduserid,
  commonSetProfile,
  registerPopupExposure,
  commonPopupClick,
  registerAuthorization,
  commonPageView,
  commonPageClick,
  simpleTrack,
  cmsExposeTrack,
  PLPProductClick,
  pdpEvent,
  registerButtonClick,
  popupEvent,
  memberInfoCompetePageClick,
  addToCart,
  editCart,
  commonOrderView,
  saveByCartTrack,
  commonCancelOrder,
  orderPageView,
  orderDetailPageView,
  drawSensorsTrack,
  drawSuccessTrack,
  searchActive,
  searchResult,
  searchResultClick,
  sensorsPageShare,
  addressManagement,
  modelAuthAsk,
  homePageEvent,
  commentTrack,
  consultantInvitationClick,
  followClick,
  setProfileAddress,
  bannerTrack,
  contentPageView,
  noMember,
  getSdkPresetProperties,
  paramsTrack,
  giftsDetailTrack
};
